package com.project.web.order.controller.common;

import com.alipay.api.internal.util.AlipaySignature;
import com.project.common.core.enums.OrderTypeEnum;
import com.project.common.core.utils.Ali.AliPayUtil;
import com.project.common.core.utils.DateUtil;
import com.project.common.core.utils.JacksonUtil;
import com.project.web.order.service.app.MbrOrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;

/**
 * 阿里支付异步通知
 *
 * @author WYY
 * @date 2021/02/06
 */
@ApiIgnore
@Controller("paymentAliNotifyController")
@RequestMapping("/order/anon/aliNotify")
public class ALiNotifyController extends BaseController {

    private static final long serialVersionUID = 108856281010693726L;

    @Resource(name = "mbrOrderServiceImpl")
    private MbrOrderService mbrOrderService;

    /**
     * 阿里APP支付回调通知
     *
     * @param request  Request对象
     * @param response Response对象
     * @return
     */
    @ResponseBody
    @RequestMapping("/appPay")
    public String appPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("\r\n ********************** 进入阿里异步通知：{} **************************", JacksonUtil.toJsonStr(request.getParameterMap()));
        // 获取支付宝异步通知消息
        Map<String, String> params = AliPayUtil.getParams(request);
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayUtil.ALI_PAY_PUBLIC_KEY, "utf-8", AliPayUtil.ALI_PAY_SIGN_TYPE);

        // 阿里App支付参数验签
        if (signVerified) {
            // 商户订单号、支付宝交易号、交易状态
            String outTradeNo = params.get("out_trade_no");
            String tradeNo = params.get("trade_no");
            String tradeStatus = params.get("trade_status");
            // 获取支付成功时间
            String gmtPayment = params.get("gmt_payment");
            //原始订单号
            String merchantOrderNo = params.get("merchant_order_no");

            Date payDate = null;
            if (StringUtils.isBlank(gmtPayment)) {
                payDate = new Date();
            } else {
                payDate = DateUtil.convertStrToDate(gmtPayment, "yyyy-MM-dd HH:mm:ss");
            }

            // 获取订单类型
            String orderTypeStr = params.get("passback_params");
            OrderTypeEnum orderType = null;
            if (StringUtils.isNotBlank(orderTypeStr)) {
                orderType = OrderTypeEnum.getEnumByCode(URLDecoder.decode(orderTypeStr, "utf-8"));
            }

            // 交易创建、交易关闭、交易结束均不处理业务
            if (tradeStatus.equals("WAIT_BUYER_PAY") || tradeStatus.equals("TRADE_CLOSED") || tradeStatus.equals("TRADE_FINISHED")) {
                log.info("\r\n ************阿里网站支付异步通知，程序不做处理:{}", JacksonUtil.toJsonStr(request.getParameterMap()));
                return "success";
            }

            // 交易支付成功
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                // 根据不同订单类型处理不同订单业务逻辑
                switch (orderType) {
                    //普通订单
                    case APP_COURSE_ORDER: {
                        mbrOrderService.handleNotifyOfPay(outTradeNo,tradeNo, payDate);
                        break;
                    }
                    default: {
                        return "fail";
                    }
                }
            }
        } else {
            // 验签失败
            log.info("\r\n *********阿里App支付验签失败:{}", JacksonUtil.toJsonStr(request.getParameterMap()));
            return "fail";
        }

        return "success";
    }
}
